#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>

using namespace std;

// 全局的锁，以及全局的条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int tickts = 100;

void *start_routine(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        // 开始就加入到等待队列中
        pthread_cond_wait(&cond, &mutex);
        cout << name << " -> " << tickts << endl;
        tickts--;
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    // pthread_t td1, td2; // 先写两个线程的  两个线程有很强的有序性
    // pthread_create(&td1, nullptr, start_routine, (void *)"thread 1");
    // pthread_create(&td2, nullptr, start_routine, (void *)"thread 2");

    pthread_t td[5];
    for (int i = 0; i < 5; i++)
    {
        char *name = new char[64];
        snprintf(name, 64, "thread %d", i + 1);
        pthread_create(td + i, nullptr, start_routine, (void *)name);
    }

    // 主线程对等待队列中的线程进行唤醒
    while (true)
    {
        sleep(1);
        //pthread_cond_signal(&cond);

        pthread_cond_broadcast(&cond);//对条件变量队列中的线程全部唤醒
        cout << "main thread wake up thread one..." << endl;
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(td[i], nullptr);
    }

    // pthread_join(td1, nullptr);
    // pthread_join(td2, nullptr);
    return 0;
}